<?php
namespace app\index\model;

class IpLocation{
    //
    public static function instance(){
        return new IpLocation();
    }
    /**
     * 查询IP归属地
     * @param string $ip 查询的IP
     * @return array [country,region,city,isp]
     */
    public function get($ip){
        $location = $this->_mine_ipLocation($ip);
        if($location){
            return $location;
        }
        $location = $this->_baidu_ipLocation($ip);
        $location = !$location ? ['country' => '中国', 'region' => '', 'city' => '', 'isp' => ''] : $location;
        return $location;
    }
    //百度地图IP定位API
    private function _baidu_ipLocation($ip){
        $options = ['http' => ['method' => 'GET', 'timeout' => 3]];
        $context = stream_context_create($options);
        $ak = config('app.baidu_iplocation_ak');
        $link = 'http://api.map.baidu.com/location/ip?ak='.$ak.'&ip='.$ip;
        $tt = file_get_contents($link, false, $context);
        $arr = json_decode($tt, true);
        if(!isset($arr['status'])){
            return null;
        }elseif($arr['status'] != 0){
            return false;
        }
        $data = explode('|', $arr['address']);
        $location = ['country' => '中国', 'region' => $data[1], 'city' => ($data[2] == 'None' ? '' : $data[2]), 'isp' => $data[4]];
        return $location;
    }
    //系统纠正的IP位置
    private function _mine_ipLocation($ip){
        return null;
    }
}